/**
 * @Filename: randomstring.cpp
 * @Description:
 * @Author: chengxiaojun
 * @Email: csforgood@gmail.com
 * @Time: 2011/11/11
 */
#include "randomstring.h"

NumberGenerator NumberGenerator::n;
StringGenerator StringGenerator::s;

NumberGenerator& NumberGenerator::instance() {
        return n;
}

NumberGenerator::NumberGenerator() {
	m_seed = (unsigned int)time(NULL);
}

NumberGenerator::~NumberGenerator() {
}
int NumberGenerator::next() {
	return rand_r(&m_seed);
}


StringGenerator::StringGenerator() {
        NumberGenerator &numgen =  NumberGenerator::instance();
        m_numgen = &numgen;
}


void StringGenerator::generate_random_string(string &str, int min_length, int max_length) {

	if(min_length <= 0) min_length = 1;
	if(max_length <= min_length) max_length = min_length;

	int len = (max_length > min_length)?m_numgen->next()%(max_length - min_length) + min_length:max_length;
	char *a = new char[len + 1];
	for(int i=0;i<len;i++) {
		a[i] = m_numgen->next()%128+1;
	}
	a[len] = 0;
	str = string(a);
        delete[] a;
}
void StringGenerator::generate_random_string(string &str, int min_length, int max_length, const char *dict) {

	if(min_length <= 0) min_length = 1;
	if(max_length <= min_length) max_length = min_length;

	int len = (max_length > min_length)?m_numgen->next()%(max_length - min_length) + min_length:max_length;
	char *a = new char[len + 1];

        int dictlen = strlen(dict);
	for(int i=0;i<len;i++) {
		a[i] = dict[m_numgen->next()%dictlen];
	}
	a[len] = 0;
	str = string(a);
        delete[] a;
}

StringGenerator::~StringGenerator() {
}

StringGenerator& StringGenerator::instance() {
        return s;
}
